"""
@File    :   jinja2.py
@Time    :   2024/03/15 10:13:53
@Author  :   Qrj
@Email   :   923207736@qq.com
@description   :   jinja2相关工具
"""

from typing import Any

from jinja2 import Environment, FileSystemLoader, select_autoescape

from src.utils.path import PathUtil

# 配置jinja2环境
jinja2_env = Environment(
    loader=FileSystemLoader(PathUtil.get_page_template_dir_path().as_posix()),
    autoescape=select_autoescape(
        [
            "html",
        ]
    ),
    enable_async=True,
)


async def render_async_template(
    template_path: str, context: dict[str, Any] | None = None, **kwargs_context
) -> str:
    """异步渲染模板

    Args:
        template_path (str): 模板相对路径
        context (dict[str, Any]): 模板上下文

    Returns:
        str: 渲染后的内容
    """
    template = jinja2_env.get_template(template_path)
    if context is None:
        context = {}
    return await template.render_async(**context, **kwargs_context)


async def render_async_from_string(
    template_string: str, context: dict[str, Any] | None = None, **kwargs_context
) -> str:
    """异步渲染模板

    Args:
        template_string (str): 需要渲染的字符串
        context (dict[str, Any]): 模板上下文

    Returns:
        str: 渲染后的内容
    """
    template = jinja2_env.from_string(template_string)
    if context is None:
        context = {}
    return await template.render_async(**context, **kwargs_context)
